import {createRouter,createWebHistory} from "vue-router";

const routes=[
    {
        path:'/',
        redirect:'/login'
    },
    {
        path:'/login',
        name:'login',
        component:()=>import('../views/Login.vue')
    },
    {
        path:'/home',
        name:'home',
        component:()=>import('../layout/Home.vue'),
        meta: { requiresAuth: true },
        children: [
            {
                path: '',
                name: 'home-default',
                redirect: '/home/dashboard'
            },
            {
                path: 'dashboard',
                name: 'dashboard',
                component: () => import('../views/Dashboard.vue')
            },
            {
                path: 'orders',
                name: 'orders',
                component: () => import('../views/order/OrderList.vue')
            },
            {
                path: 'approval-history',
                name: 'approval-history',
                component: () => import('../views/order/ApprovalHistory.vue')
            },
            {
                path: 'customers',
                name: 'customers',
                component: () => import('../views/customer/CustomerApplicationList.vue')
            },
            {
                path: 'customer-approval',
                name: 'customer-approval',
                component: () => import('../views/customer/CustomerApproval.vue')
            }
        ]
    }
]

const router=createRouter({
    history:createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token')
    
    if (to.meta.requiresAuth && !token) {
        next('/login')
    } else if (to.path === '/login' && token) {
        next('/home')
    } else {
        next()
    }
})

export default router